﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Xml.Linq;
using Grundy.CryptographicServices;
using Grundy.Key.RsaProvider;
using Grundy.Common;
using Grundy.Message;

namespace Grundy.Client.Fingerprint
{
    class Program
    {
        static void Main(string[] args)
        {
            CheckForDisplayingHelp(args);

            NodeFingerprintIdentityProvider nodeFingerprintIdentityProvider = InitializeNodeFingerprintIdentityProviderWithParameters(args);

            var hostname = Environment.MachineName;
            string f = GetFingerprint(nodeFingerprintIdentityProvider);

            File.WriteAllText("{0}.fingerprint.glf".FormatWith(hostname), f);
        }

        private static NodeFingerprintIdentityProvider InitializeNodeFingerprintIdentityProviderWithParameters(string[] args)
        {
            var nodeFingerprintIdentityProvider = new NodeFingerprintIdentityProvider();
            if (args.ContainsIgnoreCase("-mac"))
            {
                nodeFingerprintIdentityProvider.IgnoreMacAddresses = true;
            }
            return nodeFingerprintIdentityProvider;
        }

        private static void CheckForDisplayingHelp(string[] args)
        {
            if (args.ContainsIgnoreCase("/?") || args.ContainsIgnoreCase("-help"))
            {
                Console.WriteLine("Options: ");
                Console.WriteLine("-mac:     Mark MAC Addresses as optional.");
            }
        }

        private static string GetFingerprint(NodeFingerprintIdentityProvider nodeFingerprintIdentityProvider)
        {
            var identifiers = nodeFingerprintIdentityProvider.GetIdentifiers();
            var fingerprint = new CryptographicServices.Fingerprint { CreatedOn = DateTime.UtcNow, Identifiers = identifiers };
            var csp = new RsaProvider(Client_RsaProvider_Private.Key);
            var container = csp.Sign(fingerprint, ContainerSigneeType.Client);
            return container.Serialize();
        }
    }
}
